import React, { useState, useEffect } from 'react';
import { Card, Table, Avatar, Badge, Typography, Button, Space, Input, message, Tooltip, Empty } from 'antd';
import { SearchOutlined, MessageOutlined, UserOutlined, TeamOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';
import chatService from '../services/chatService';

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

const { Title, Text } = Typography;
const { Search } = Input;

const ChatsPage = () => {
  const [loading, setLoading] = useState(false);
  const [chats, setChats] = useState([]);
  const [searchText, setSearchText] = useState('');
  const navigate = useNavigate();

  // 获取所有聊天
  const fetchChats = async () => {
    try {
      setLoading(true);
      const fetchedChats = await chatService.getChats();
      setChats(fetchedChats);
    } catch (error) {
      console.error('获取聊天失败:', error);
      message.error('获取聊天列表失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchChats();
  }, []);

  // 过滤聊天
  const filteredChats = chats.filter(chat => 
    chat.name.toLowerCase().includes(searchText.toLowerCase()) || 
    (chat.lastMessage && chat.lastMessage.message.toLowerCase().includes(searchText.toLowerCase()))
  );

  // 打开聊天
  const openChat = (chatId) => {
    navigate(`/chat/${chatId}`);
  };

  // 表格列定义
  const columns = [
    {
      title: '联系人',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          <Avatar 
            size="large" 
            icon={record.isGroup ? <TeamOutlined /> : <UserOutlined />}
            src={record.profilePicUrl}
          />
          <Space direction="vertical" size={0}>
            <Text strong>{text}</Text>
            <Text type="secondary" style={{ fontSize: '12px' }}>{record.phone}</Text>
          </Space>
        </Space>
      ),
    },
    {
      title: '最近消息',
      dataIndex: 'lastMessage',
      key: 'lastMessage',
      render: (lastMessage, record) => (
        lastMessage ? (
          <Space direction="vertical" size={0}>
            <Text ellipsis={{ tooltip: typeof lastMessage.message === 'string' ? lastMessage.message : '无法显示消息' }} style={{ maxWidth: 250 }}>
              {typeof lastMessage.message === 'string' ? lastMessage.message : JSON.stringify(lastMessage.message)}
            </Text>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {dayjs(lastMessage.timestamp).fromNow()}
            </Text>
          </Space>
        ) : <Text type="secondary">无消息</Text>
      ),
    },
    {
      title: '未读',
      dataIndex: 'unreadCount',
      key: 'unreadCount',
      width: 80,
      align: 'center',
      render: (unreadCount) => (
        unreadCount > 0 ? (
          <Badge count={unreadCount} style={{ backgroundColor: '#52c41a' }} />
        ) : (
          <Badge count={0} showZero={false} />
        )
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Button 
          type="primary" 
          icon={<MessageOutlined />}
          onClick={() => openChat(record.id)}
        >
          聊天
        </Button>
      ),
    },
  ];

  return (
    <Card 
      title={<Title level={4}>所有聊天</Title>}
      extra={
        <Button type="primary" onClick={fetchChats}>
          刷新
        </Button>
      }
    >
      <Search
        placeholder="搜索聊天..."
        allowClear
        enterButton={<SearchOutlined />}
        size="large"
        value={searchText}
        onChange={e => setSearchText(e.target.value)}
        style={{ marginBottom: 16 }}
      />
      
      <Table
        columns={columns}
        dataSource={filteredChats}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 10 }}
        locale={{
          emptyText: <Empty description="暂无聊天" image={Empty.PRESENTED_IMAGE_SIMPLE} />
        }}
        onRow={(record) => ({
          onClick: () => openChat(record.id),
          style: { cursor: 'pointer' }
        })}
      />
    </Card>
  );
};

export default ChatsPage; 